#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
应用平台检测器
用于自动检测应用所属平台
"""

import os
from pathlib import Path
from typing import Dict, List, Optional

from src.utils.logger import get_logger

class PlatformDetector:
    """应用平台检测器"""
    
    # 平台特征映射
    PLATFORM_SIGNATURES = {
        "windows": {
            "extensions": [".exe", ".dll", ".msix", ".appx", ".msi"],
            "files": ["AppxManifest.xml"],
            "headers": [b"MZ", b"PE\0\0"]
        },
        "macos": {
            "extensions": [".app", ".dmg", ".framework", ".pkg"],
            "files": ["Info.plist", "Contents/Info.plist"],
            "headers": [b"bplist", b"applsign"]
        },
        "linux": {
            "extensions": [".deb", ".rpm", ".so", ".appimage"],
            "files": ["DEBIAN/control", "usr/share/applications"],
            "headers": [b"\x7fELF"]
        },
        "android": {
            "extensions": [".apk", ".aab", ".dex"],
            "files": ["AndroidManifest.xml", "classes.dex", "META-INF/MANIFEST.MF"],
            "headers": [b"PK\x03\x04", b"dex\n"]
        },
        "ios": {
            "extensions": [".ipa", ".framework", ".xcarchive"],
            "files": ["Info.plist", "Payload/", "META-INF/rights.xml"],
            "headers": [b"bplist", b"PK\x03\x04"]
        },
        "harmony": {
            "extensions": [".hap", ".app"],
            "files": ["module.json", "resources.index"],
            "headers": []
        }
    }
    
    def __init__(self, app_path: Path):
        """
        初始化平台检测器
        
        Args:
            app_path: 应用路径
        """
        self.app_path = Path(app_path)
        self.logger = get_logger("PlatformDetector")
        self.logger.info(f"初始化平台检测器，目标路径: {app_path}")
    
    def detect(self) -> str:
        """
        检测应用平台
        
        Returns:
            检测到的平台名称，如果无法确定则返回默认平台
        """
        platform_scores = self._calculate_platform_scores()
        
        if not platform_scores:
            self.logger.warning(f"无法确定应用平台，使用默认平台: windows")
            return "windows"
        
        # 找出得分最高的平台
        detected_platform = max(platform_scores.items(), key=lambda x: x[1])[0]
        self.logger.info(f"检测到应用平台: {detected_platform}")
        
        return detected_platform
    
    def _calculate_platform_scores(self) -> Dict[str, int]:
        """
        计算各平台得分
        
        Returns:
            平台得分字典
        """
        scores = {platform: 0 for platform in self.PLATFORM_SIGNATURES.keys()}
        
        # 检查文件扩展名
        if self.app_path.is_file():
            for platform, signatures in self.PLATFORM_SIGNATURES.items():
                if any(self.app_path.name.endswith(ext) for ext in signatures["extensions"]):
                    scores[platform] += 2
        
        # 检查目录结构和文件
        if self.app_path.is_dir():
            for platform, signatures in self.PLATFORM_SIGNATURES.items():
                for file_pattern in signatures["files"]:
                    file_path = self.app_path / file_pattern
                    if file_path.exists():
                        scores[platform] += 3
                        
                # 简单搜索扩展名
                for root, _, files in os.walk(self.app_path, topdown=True):
                    for file in files:
                        for ext in signatures["extensions"]:
                            if file.endswith(ext):
                                scores[platform] += 1
                                break
                    
                    # 限制遍历深度
                    if root.count(os.sep) - self.app_path.as_posix().count(os.sep) > 3:
                        break
        
        # 检查二进制头部签名
        if self.app_path.is_file():
            with open(self.app_path, 'rb') as f:
                header = f.read(16)
                for platform, signatures in self.PLATFORM_SIGNATURES.items():
                    for header_sig in signatures["headers"]:
                        if header.startswith(header_sig):
                            scores[platform] += 3
        
        self.logger.debug(f"平台得分: {scores}")
        return scores 
